require 'rubygems'
require 'xml/libxml'
require 'family_tree_api/search/person'

module FamilyTreeApi
  module Match
    NS = ['fs:http://api.familysearch.org/familytree/v1','fsapi:http://api.familysearch.org/v1']
    class Base
      attr_accessor :ref, :confidence, :person, :parents, :spouses
      
      def father
        @father ||= @parents.select{|p| p.role == "Father"}.first
        @father
      end
      
      def mother
        @mother ||= @parents.select{|p| p.role == "Mother"}.first
        @mother
      end
      
      def self.parse (m_element)
        match = self.new
        match.ref = m_element.attributes['ref']
        match.confidence = m_element.attributes['confidence']
        m_element.each do |e|
          case e.name
          when 'person'
            match.person = Search::Person.parse(e)
          when 'parents'
            match.parents = e.children.collect do |p|
              Search::Parent.parse(p)
            end
          when 'spouses'
            match.spouses = e.children.collect do |s|
              Search::Person.parse(s)
            end
          # when 'children'
          #   result.children = e.children.collect do |c|
          #     Person.parse(c)
          #   end
          end
        end
        
        match
      end
    end
    
    class Matches
      def self.parse(xml)
        xp = XML::Parser.new() 
        xp.string = xml
        doc = xp.parse
        results = doc.find("//fs:matches/fs:match",NS).collect { |m_element| FamilyTreeApi::Match::Base.parse(m_element) }
      end
    end
  end
end